import {EntityManager, Repository} from "typeorm";
import {ResultUtils} from "@/utils/resultUtils";

/**
 * 事务
 */
export class Tx {
    constructor(public repository: Repository<any>) {
    }

    async txExec<T = any>(runInTransaction: (entityManager: EntityManager) => Promise<T>) {
        try {
            const result = await this.repository.manager.transaction(async (transactionalEntityManager) => {
                return runInTransaction(transactionalEntityManager);
            });
            return ResultUtils.success(result);
        } catch (e) {
            return ResultUtils.error(null, e.message, e);
        }
    }
}
